import axios from "axios";
import store from "../store";
import router from "../router";

// create an axios instance
const service = axios.create({
  // baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 180000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // if (store.state.token) {
    // config.headers.token = store.state.token;
    // }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    if (typeof response.data.errCode !== "undefined") {
      // 0 的情况下javascript会认为是false
      if (response.data.errCode === 0) {
        return response.data;
      } else {
        console.log("error - " + response.data.errCode); // for debug
        if (response.data.errCode === 401) {
          console.log("会话已过期，请重新登录");
          // 登录过期，需要重新登录，同时清空token和localStorage
          store.commit("setToken", "");
          localStorage.removeItem("currentUser");
          // 跳转到login页面
          router.replace({ path: "/login" });
        } else {
          // eslint-disable-next-line prefer-promise-reject-errors
          return Promise.reject(response.data.errCode.toString());
        }
      }
    }
  },
  error => {
    console.log("err" + error); // for debug
    if (error && error.response && error.response.status) {
      switch (error.response.status) {
        case 401:
          console.log("会话已过期，请重新登录");
          // 登录过期，需要重新登录，同时清空token和localStorage
          store.commit("setToken", "");
          localStorage.removeItem("currentUser");
          // 跳转到login页面
          router.replace({ path: "/login" });
          break;
        default:
          break;
      }
    }
    return Promise.reject(error.response.status.toString());
  }
);

export default service;
